/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.railway.app;

import com.railway.utils.CustomTableModel;
import com.railway.classes.Route;
import com.railway.classes.Train;
import com.railway.utils.CustomScrollBarUI;
import com.railway.utils.RestServer;
import com.railway.utils.TextFieldLimiter;
import com.railway.utils.Toast;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.text.AbstractDocument;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Kenny
 */
public class SchedulePanel extends javax.swing.JPanel {

    Image imgArrow = new ImageIcon(this.getClass().getResource("/com/railway/image/arrow.png")).getImage();
    private ArrayList<String> colName;
    private ArrayList<ArrayList<Object>> rowData;
    private JSONObject json;
    private JSONArray jsonArray;
    private CustomTableModel ctmModel;
    private SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    private SimpleDateFormat current = new SimpleDateFormat("hh:mm a");
    private CardLayout cl;
    private Vector routeData;
    private Vector trainData;
    private Calendar c = Calendar.getInstance();
    private Date initDate;
    private Date maxDate;
    private DefaultComboBoxModel cbbRouteModel;
    private DefaultComboBoxModel cbbTrainModel;
    private String status = "ACV";
    private Integer shid;

    /**
     * Creates new form RoutePanel
     */
    public SchedulePanel() {
        c.set(1970, 0, 1, 5, 0, 0);
        c.set(Calendar.MILLISECOND, 0);
        initDate = c.getTime();
        c.set(1970, 0, 1, 23, 0, 0);
        c.set(Calendar.MILLISECOND, 0);
        maxDate = c.getTime();
        initComponents();
        jspScheduleScroller.getViewport().setBackground(Color.WHITE);
        populateTableData();
        getActiveRoute(jcbxMActiveRoute);
        getActiveTrain(jcbxMTrain);
        cl = (CardLayout) jpScheduleCard.getLayout();
    }

    private void populateTableData() {
        new Thread() {
            @Override
            public void run() {
                colName = new ArrayList<>();
                SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
                SimpleDateFormat current = new SimpleDateFormat("HH:mm:ss");
                colName.add("Schedule ID");
                colName.add("Schedule Name");
                colName.add("Departure Time");
                colName.add("Route ID");
                colName.add("Route Name");
                colName.add("Train ID");
                colName.add("Train Name");
                colName.add("Status");
                String data = RestServer.httpGet("schedule", "");
                try {
                    json = new JSONObject(data);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                        int status = json.getInt("status");
                        if (status == 200) {
                            rowData = new ArrayList<>();
                            jsonArray = json.getJSONArray("content");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                ArrayList<Object> temp = new ArrayList<>();
                                temp.add(jsonArray.getJSONObject(i).getInt("shid"));
                                temp.add(jsonArray.getJSONObject(i).getString("scheduleName"));
                                temp.add(format.format(current.parse(jsonArray.getJSONObject(i).getString("departureTime"))));
                                temp.add(jsonArray.getJSONObject(i).getString("rid"));
                                temp.add(jsonArray.getJSONObject(i).getString("routeName"));
                                temp.add(jsonArray.getJSONObject(i).getString("trainId"));
                                temp.add(jsonArray.getJSONObject(i).getString("trainName"));
                                temp.add((jsonArray.getJSONObject(i).getString("status").equals("ACV")) ? "Active" : "Inactive");
                                rowData.add(temp);
                            }
                            ctmModel = new CustomTableModel(colName, rowData);
                            jtbSchedule.setModel(ctmModel);
                            jtbSchedule.removeColumn(jtbSchedule.getColumnModel().getColumn(0));
                            jtbSchedule.removeColumn(jtbSchedule.getColumnModel().getColumn(2));
                            jtbSchedule.removeColumn(jtbSchedule.getColumnModel().getColumn(3));
                        }
                    } else {
                        Toast.makeText(getParent(), json.getString("message"), Toast.LENGTH_LONG).display();
                    }
                } catch (JSONException | ParseException ex) {
                    Logger.getLogger(SchedulePanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }.start();
    }

    private void getActiveRoute(final JComboBox cbb) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                routeData = new Vector();
                String result = RestServer.httpGet("route/active", "");
                try {
                    json = new JSONObject(result);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                        int statuscode = json.getInt("status");
                        if (statuscode == 200) {
                            jsonArray = json.getJSONArray("content");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                Route route = new Route();
                                route.setRid(jsonArray.getJSONObject(i).getInt("rid"));
                                route.setRouteName(jsonArray.getJSONObject(i).getString("routeName"));
                                routeData.add(route);
                            }
                            cbbRouteModel = new DefaultComboBoxModel(routeData);
                            cbb.setModel(cbbRouteModel);
                        } else {
                            Toast.makeText(getParent(), "No active routes found.", Toast.LENGTH_SHORT).display();
                        }
                    } else {
                        Toast.makeText(getParent(), "Error occured, please try again later.", Toast.LENGTH_SHORT).display();
                    }
                } catch (JSONException ex) {
                }
            }
        }).start();
    }

    private void getActiveTrain(final JComboBox cbb) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                trainData = new Vector();
                String result = RestServer.httpGet("train/active", "");
                try {
                    json = new JSONObject(result);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                        int statuscode = json.getInt("status");
                        if (statuscode == 200) {
                            jsonArray = json.getJSONArray("content");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                Train train = new Train();
                                train.setTrainId(jsonArray.getJSONObject(i).getInt("trainId"));
                                train.setTrainName(jsonArray.getJSONObject(i).getString("trainName"));
                                trainData.add(train);
                            }
                            cbbTrainModel = new DefaultComboBoxModel(trainData);
                            cbb.setModel(cbbTrainModel);
                        } else {
                            Toast.makeText(getParent(), "All trains are unavailable currently.", Toast.LENGTH_SHORT).display();
                        }
                    } else {
                        Toast.makeText(getParent(), "Error occured, please try again later.", Toast.LENGTH_SHORT).display();
                    }
                } catch (JSONException ex) {
                }
            }
        }).start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jbgAStatus = new javax.swing.ButtonGroup();
        jbgMStatus = new javax.swing.ButtonGroup();
        jpSchedule = new javax.swing.JPanel();
        jpScheduleContent = new javax.swing.JPanel();
        jlblScheduleTitle = new javax.swing.JLabel();
        jsprSchedule = new javax.swing.JSeparator();
        jspScheduleScroller = new javax.swing.JScrollPane();
        jtbSchedule = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jbtAddSchedule = new javax.swing.JButton();
        jbtModifySchedule = new javax.swing.JButton();
        jpScheduleCard = new javax.swing.JPanel();
        jpNullCard = new javax.swing.JPanel();
        jpAddCard = new javax.swing.JPanel();
        jpAddArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), imgArrow.getHeight(this), this);
            }
        };
        jpAddSchedule = new javax.swing.JPanel();
        jlblASelectRoute = new javax.swing.JLabel();
        jcbxAActiveRoute = new javax.swing.JComboBox();
        jlblAScheduleName = new javax.swing.JLabel();
        jtfAScheduleName = new javax.swing.JTextField();
        jlblADepartureTime = new javax.swing.JLabel();
        jspiADepartureTime = new javax.swing.JSpinner(
            new SpinnerDateModel(initDate, initDate, maxDate, Calendar.MINUTE)
        );
        JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(jspiADepartureTime, "hh:mm a");
        timeEditor.getTextField().setEditable(false);
        jspiADepartureTime.setEditor(timeEditor);
        jlblATrain = new javax.swing.JLabel();
        jcbxATrain = new javax.swing.JComboBox();
        jbtAClear = new javax.swing.JButton();
        jbtASubmit = new javax.swing.JButton();
        jlblAStatus = new javax.swing.JLabel();
        jrbAActive = new javax.swing.JRadioButton();
        jrbAInactive = new javax.swing.JRadioButton();
        jpModifyCard = new javax.swing.JPanel();
        jpModifyArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), imgArrow.getHeight(this), this);
            }
        };
        jpModifySchedule = new javax.swing.JPanel();
        jlblMSelectRoute = new javax.swing.JLabel();
        jcbxMActiveRoute = new javax.swing.JComboBox();
        jlblMScheduleName = new javax.swing.JLabel();
        jtfMScheduleName = new javax.swing.JTextField();
        jlblMDepartureTime = new javax.swing.JLabel();
        jspiMDepartureTime = new javax.swing.JSpinner(
            new SpinnerDateModel(initDate, initDate, maxDate, Calendar.MINUTE)
        );
        JSpinner.DateEditor mTimeEditor = new JSpinner.DateEditor(jspiMDepartureTime, "hh:mm a");
        mTimeEditor.getTextField().setEditable(false);
        jspiMDepartureTime.setEditor(mTimeEditor);
        jlblMTrain = new javax.swing.JLabel();
        jcbxMTrain = new javax.swing.JComboBox();
        jbtMSubmit = new javax.swing.JButton();
        jlblMStatus = new javax.swing.JLabel();
        jrbMActive = new javax.swing.JRadioButton();
        jrbMInactive = new javax.swing.JRadioButton();
        jpScheduleArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), getHeight(), this);
            }
        };

        setPreferredSize(new java.awt.Dimension(870, 460));
        setLayout(null);

        jpSchedule.setBackground(new java.awt.Color(220, 220, 220));
        jpSchedule.setLayout(null);

        jpScheduleContent.setBackground(new java.awt.Color(255, 255, 255));
        jpScheduleContent.setLayout(null);

        jlblScheduleTitle.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jlblScheduleTitle.setText("SCHEDULES");
        jpScheduleContent.add(jlblScheduleTitle);
        jlblScheduleTitle.setBounds(395, 0, 460, 20);
        jpScheduleContent.add(jsprSchedule);
        jsprSchedule.setBounds(395, 20, 460, 5);

        jspScheduleScroller.getVerticalScrollBar().setUI(new CustomScrollBarUI());

        jtbSchedule.setAutoCreateRowSorter(true);
        jtbSchedule.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbSchedule.getTableHeader().setReorderingAllowed(false);
        jspScheduleScroller.setViewportView(jtbSchedule);

        jpScheduleContent.add(jspScheduleScroller);
        jspScheduleScroller.setBounds(395, 25, 460, 400);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jPanel1.setLayout(null);

        jbtAddSchedule.setBackground(new java.awt.Color(52, 73, 94));
        jbtAddSchedule.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtAddSchedule.setForeground(new java.awt.Color(255, 255, 255));
        jbtAddSchedule.setText("Add Schedule");
        jbtAddSchedule.setFocusPainted(false);
        jbtAddSchedule.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAddScheduleActionPerformed(evt);
            }
        });
        jPanel1.add(jbtAddSchedule);
        jbtAddSchedule.setBounds(5, 5, 170, 50);

        jbtModifySchedule.setBackground(new java.awt.Color(52, 73, 94));
        jbtModifySchedule.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtModifySchedule.setForeground(new java.awt.Color(255, 255, 255));
        jbtModifySchedule.setText("Modify Schedule");
        jbtModifySchedule.setFocusPainted(false);
        jbtModifySchedule.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtModifyScheduleActionPerformed(evt);
            }
        });
        jPanel1.add(jbtModifySchedule);
        jbtModifySchedule.setBounds(210, 5, 170, 50);

        jpScheduleCard.setBackground(new java.awt.Color(255, 255, 255));
        jpScheduleCard.setLayout(new java.awt.CardLayout());

        jpNullCard.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpNullCardLayout = new javax.swing.GroupLayout(jpNullCard);
        jpNullCard.setLayout(jpNullCardLayout);
        jpNullCardLayout.setHorizontalGroup(
            jpNullCardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 375, Short.MAX_VALUE)
        );
        jpNullCardLayout.setVerticalGroup(
            jpNullCardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 360, Short.MAX_VALUE)
        );

        jpScheduleCard.add(jpNullCard, "null");

        jpAddCard.setBackground(new java.awt.Color(255, 255, 255));
        jpAddCard.setLayout(null);

        jpAddArrow.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpAddArrowLayout = new javax.swing.GroupLayout(jpAddArrow);
        jpAddArrow.setLayout(jpAddArrowLayout);
        jpAddArrowLayout.setHorizontalGroup(
            jpAddArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 170, Short.MAX_VALUE)
        );
        jpAddArrowLayout.setVerticalGroup(
            jpAddArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        jpAddCard.add(jpAddArrow);
        jpAddArrow.setBounds(0, 0, 170, 10);

        jpAddSchedule.setBackground(new java.awt.Color(255, 255, 255));
        jpAddSchedule.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpAddSchedule.setLayout(null);

        jlblASelectRoute.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblASelectRoute.setText("Select Route");
        jpAddSchedule.add(jlblASelectRoute);
        jlblASelectRoute.setBounds(10, 20, 110, 30);

        jcbxAActiveRoute.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpAddSchedule.add(jcbxAActiveRoute);
        jcbxAActiveRoute.setBounds(120, 20, 240, 30);

        jlblAScheduleName.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblAScheduleName.setText("Schedule Name");
        jpAddSchedule.add(jlblAScheduleName);
        jlblAScheduleName.setBounds(10, 65, 110, 30);

        AbstractDocument aDoc = (AbstractDocument)jtfAScheduleName.getDocument();
        aDoc.setDocumentFilter(new TextFieldLimiter(".{0,4}"));
        jtfAScheduleName.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpAddSchedule.add(jtfAScheduleName);
        jtfAScheduleName.setBounds(120, 65, 240, 30);

        jlblADepartureTime.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblADepartureTime.setText("Departure Time");
        jpAddSchedule.add(jlblADepartureTime);
        jlblADepartureTime.setBounds(10, 110, 110, 30);

        jspiADepartureTime.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpAddSchedule.add(jspiADepartureTime);
        jspiADepartureTime.setBounds(120, 110, 240, 30);

        jlblATrain.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblATrain.setText("Assigned Train");
        jpAddSchedule.add(jlblATrain);
        jlblATrain.setBounds(10, 155, 110, 30);

        jcbxATrain.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpAddSchedule.add(jcbxATrain);
        jcbxATrain.setBounds(120, 155, 240, 30);

        jbtAClear.setBackground(new java.awt.Color(39, 174, 96));
        jbtAClear.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtAClear.setForeground(new java.awt.Color(255, 255, 255));
        jbtAClear.setText("Clear");
        jbtAClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAClearActionPerformed(evt);
            }
        });
        jpAddSchedule.add(jbtAClear);
        jbtAClear.setBounds(10, 290, 150, 45);

        jbtASubmit.setBackground(new java.awt.Color(39, 174, 96));
        jbtASubmit.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtASubmit.setForeground(new java.awt.Color(255, 255, 255));
        jbtASubmit.setText("Submit");
        jbtASubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtASubmitActionPerformed(evt);
            }
        });
        jpAddSchedule.add(jbtASubmit);
        jbtASubmit.setBounds(215, 290, 150, 45);

        jlblAStatus.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblAStatus.setText("Status");
        jpAddSchedule.add(jlblAStatus);
        jlblAStatus.setBounds(10, 200, 110, 30);

        jrbAActive.setBackground(new java.awt.Color(255, 255, 255));
        jbgAStatus.add(jrbAActive);
        jrbAActive.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jrbAActive.setSelected(true);
        jrbAActive.setText("Active");
        jrbAActive.setActionCommand("ACV");
        jrbAActive.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbAActiveActionPerformed(evt);
            }
        });
        jpAddSchedule.add(jrbAActive);
        jrbAActive.setBounds(140, 200, 90, 30);

        jrbAInactive.setBackground(new java.awt.Color(255, 255, 255));
        jbgAStatus.add(jrbAInactive);
        jrbAInactive.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jrbAInactive.setText("Inactive");
        jrbAInactive.setActionCommand("INV");
        jrbAInactive.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbAInactiveActionPerformed(evt);
            }
        });
        jpAddSchedule.add(jrbAInactive);
        jrbAInactive.setBounds(240, 200, 90, 30);

        jpAddCard.add(jpAddSchedule);
        jpAddSchedule.setBounds(0, 10, 375, 350);

        jpScheduleCard.add(jpAddCard, "addschedule");

        jpModifyCard.setBackground(new java.awt.Color(255, 255, 255));
        jpModifyCard.setLayout(null);

        jpModifyArrow.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpModifyArrowLayout = new javax.swing.GroupLayout(jpModifyArrow);
        jpModifyArrow.setLayout(jpModifyArrowLayout);
        jpModifyArrowLayout.setHorizontalGroup(
            jpModifyArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 170, Short.MAX_VALUE)
        );
        jpModifyArrowLayout.setVerticalGroup(
            jpModifyArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        jpModifyCard.add(jpModifyArrow);
        jpModifyArrow.setBounds(210, 0, 170, 10);

        jpModifySchedule.setBackground(new java.awt.Color(255, 255, 255));
        jpModifySchedule.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpModifySchedule.setLayout(null);

        jlblMSelectRoute.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMSelectRoute.setText("Route");
        jpModifySchedule.add(jlblMSelectRoute);
        jlblMSelectRoute.setBounds(10, 65, 110, 30);

        jcbxMActiveRoute.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpModifySchedule.add(jcbxMActiveRoute);
        jcbxMActiveRoute.setBounds(120, 65, 240, 30);

        jlblMScheduleName.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMScheduleName.setText("Schedule Name");
        jpModifySchedule.add(jlblMScheduleName);
        jlblMScheduleName.setBounds(10, 20, 110, 30);

        AbstractDocument mDoc = (AbstractDocument)jtfMScheduleName.getDocument();
        mDoc.setDocumentFilter(new TextFieldLimiter(".{0,4}"));
        jtfMScheduleName.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpModifySchedule.add(jtfMScheduleName);
        jtfMScheduleName.setBounds(120, 20, 240, 30);

        jlblMDepartureTime.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMDepartureTime.setText("Departure Time");
        jpModifySchedule.add(jlblMDepartureTime);
        jlblMDepartureTime.setBounds(10, 110, 110, 30);

        jspiMDepartureTime.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpModifySchedule.add(jspiMDepartureTime);
        jspiMDepartureTime.setBounds(120, 110, 240, 30);

        jlblMTrain.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMTrain.setText("Assigned Train");
        jpModifySchedule.add(jlblMTrain);
        jlblMTrain.setBounds(10, 155, 110, 30);

        jcbxMTrain.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpModifySchedule.add(jcbxMTrain);
        jcbxMTrain.setBounds(120, 155, 240, 30);

        jbtMSubmit.setBackground(new java.awt.Color(39, 174, 96));
        jbtMSubmit.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtMSubmit.setForeground(new java.awt.Color(255, 255, 255));
        jbtMSubmit.setText("Submit");
        jbtMSubmit.setFocusPainted(false);
        jbtMSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtMSubmitActionPerformed(evt);
            }
        });
        jpModifySchedule.add(jbtMSubmit);
        jbtMSubmit.setBounds(215, 290, 150, 45);

        jlblMStatus.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMStatus.setText("Status");
        jpModifySchedule.add(jlblMStatus);
        jlblMStatus.setBounds(10, 200, 110, 30);

        jrbMActive.setBackground(new java.awt.Color(255, 255, 255));
        jbgMStatus.add(jrbMActive);
        jrbMActive.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jrbMActive.setSelected(true);
        jrbMActive.setText("Active");
        jrbMActive.setActionCommand("ACV");
        jrbMActive.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbMActiveActionPerformed(evt);
            }
        });
        jpModifySchedule.add(jrbMActive);
        jrbMActive.setBounds(140, 200, 90, 30);

        jrbMInactive.setBackground(new java.awt.Color(255, 255, 255));
        jbgMStatus.add(jrbMInactive);
        jrbMInactive.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jrbMInactive.setText("Inactive");
        jrbMInactive.setActionCommand("INV");
        jrbMInactive.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbMInactiveActionPerformed(evt);
            }
        });
        jpModifySchedule.add(jrbMInactive);
        jrbMInactive.setBounds(240, 200, 90, 30);

        jpModifyCard.add(jpModifySchedule);
        jpModifySchedule.setBounds(0, 10, 375, 350);

        jpScheduleCard.add(jpModifyCard, "modifyschedule");

        jPanel1.add(jpScheduleCard);
        jpScheduleCard.setBounds(5, 55, 375, 360);

        jpScheduleContent.add(jPanel1);
        jPanel1.setBounds(5, 5, 385, 420);

        jpSchedule.add(jpScheduleContent);
        jpScheduleContent.setBounds(5, 5, 860, 430);

        add(jpSchedule);
        jpSchedule.setBounds(0, 20, 870, 440);

        javax.swing.GroupLayout jpScheduleArrowLayout = new javax.swing.GroupLayout(jpScheduleArrow);
        jpScheduleArrow.setLayout(jpScheduleArrowLayout);
        jpScheduleArrowLayout.setHorizontalGroup(
            jpScheduleArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 150, Short.MAX_VALUE)
        );
        jpScheduleArrowLayout.setVerticalGroup(
            jpScheduleArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 20, Short.MAX_VALUE)
        );

        add(jpScheduleArrow);
        jpScheduleArrow.setBounds(360, 0, 150, 20);
    }// </editor-fold>//GEN-END:initComponents

    private void jbtAddScheduleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAddScheduleActionPerformed
        jbtAddSchedule.setBackground(new Color(44, 62, 80));
        jbtModifySchedule.setBackground(new Color(52, 73, 94));
        cl.show(jpScheduleCard, "addschedule");
        getActiveRoute(jcbxAActiveRoute);
        getActiveTrain(jcbxATrain);
    }//GEN-LAST:event_jbtAddScheduleActionPerformed

    private void jbtModifyScheduleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtModifyScheduleActionPerformed
        if (jtbSchedule.getSelectedRow() >= 0) {
            try {
                jbtAddSchedule.setBackground(new Color(52, 73, 94));
                jbtModifySchedule.setBackground(new Color(44, 62, 80));
                cl.show(jpScheduleCard, "modifyschedule");
                Route selectedRoute = new Route(
                        Integer.parseInt(jtbSchedule.getModel().getValueAt(jtbSchedule.getSelectedRow(), 3).toString()),
                        jtbSchedule.getValueAt(jtbSchedule.getSelectedRow(), 3).toString(), "ACV");
                Train selectedTrain = new Train(
                        Integer.parseInt(jtbSchedule.getModel().getValueAt(jtbSchedule.getSelectedRow(), 5).toString()),
                        jtbSchedule.getValueAt(jtbSchedule.getSelectedRow(), 4).toString());
                jcbxMActiveRoute.setSelectedItem(selectedRoute);
                jcbxMTrain.setSelectedItem(selectedTrain);
                jtfMScheduleName.setText(
                        jtbSchedule.getValueAt(jtbSchedule.getSelectedRow(), 0).toString());
                shid = (Integer) jtbSchedule.getModel().getValueAt(jtbSchedule.getSelectedRow(), 0);
                System.out.println("" + shid);
                if (jtbSchedule.getValueAt(
                        jtbSchedule.getSelectedRow(), 4).equals("Active")) {
                    jrbMActive.setSelected(true);
                } else {
                    jrbMInactive.setSelected(true);
                }
                Date dtime = current.parse(
                        jtbSchedule.getValueAt(jtbSchedule.getSelectedRow(), 1).toString());
                jspiMDepartureTime.setValue(dtime);
            } catch (ParseException ex) {
                Logger.getLogger(SchedulePanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            Toast.makeText(this, "Please make selection fron the table first.", Toast.LENGTH_SHORT).display();
        }
    }//GEN-LAST:event_jbtModifyScheduleActionPerformed

    private void jbtAClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAClearActionPerformed
        jcbxAActiveRoute.setSelectedIndex(0);
        jcbxATrain.setSelectedIndex(0);
        jtfAScheduleName.setText(null);
        jspiADepartureTime.setValue(initDate);
    }//GEN-LAST:event_jbtAClearActionPerformed

    private void jbtASubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtASubmitActionPerformed
        if (!jtfAScheduleName.getText().equals("")) {
            Map<String, Object> data = new HashMap<>();
            data.put("sname", jtfAScheduleName.getText().toUpperCase());
            data.put("dtime", format.format((Date) jspiADepartureTime.getValue()));
            data.put("status", status);
            data.put("rid", ((Route) jcbxAActiveRoute.getSelectedItem()).getRid());
            data.put("tid", ((Train) jcbxATrain.getSelectedItem()).getTrainId());
            String result = RestServer.httpPost("schedule", data);
            try {
                json = new JSONObject(result);
                boolean error = json.optBoolean("error");
                if (!error) {
                    int statuscode = json.getInt("status");
                    if (statuscode == 200) {
                        Toast.makeText(this, "Schedule added successfully", Toast.LENGTH_SHORT).display();
                        populateTableData();
                    } else {
                        Toast.makeText(this, "Unable to add schedule now, please try again later.", Toast.LENGTH_SHORT).display();
                    }
                } else {
                    Toast.makeText(this, "Error occured, please try again later.", Toast.LENGTH_SHORT).display();
                }
            } catch (JSONException ex) {
            }
        } else {
            Toast.makeText(this, "Please fill in all fields first", Toast.LENGTH_SHORT).display();
        }
    }//GEN-LAST:event_jbtASubmitActionPerformed

    private void jrbAActiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbAActiveActionPerformed
        status = evt.getActionCommand();
    }//GEN-LAST:event_jrbAActiveActionPerformed

    private void jrbAInactiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbAInactiveActionPerformed
        status = evt.getActionCommand();
    }//GEN-LAST:event_jrbAInactiveActionPerformed

    private void jbtMSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtMSubmitActionPerformed
        if (!jtfMScheduleName.getText().equals("")) {
            Map<String, Object> data = new HashMap<>();
            System.out.println(jtfMScheduleName.getText().toUpperCase());
            data.put("sname", jtfMScheduleName.getText().toUpperCase());
            data.put("dtime", format.format((Date) jspiMDepartureTime.getValue()));
            data.put("status", status);
            data.put("rid", ((Route) jcbxMActiveRoute.getSelectedItem()).getRid());
            data.put("tid", ((Train) jcbxMTrain.getSelectedItem()).getTrainId());
            String result = RestServer.httpPut("schedule", data, "" + shid);
            try {
                json = new JSONObject(result);
                boolean error = json.optBoolean("error");
                if (!error) {
                    int statuscode = json.getInt("status");
                    if (statuscode == 200) {
                        Toast.makeText(this, "Schedule updated successfully.", Toast.LENGTH_SHORT).display();
                        populateTableData();
                    } else {
                        Toast.makeText(this, "Schedule did not updated, have you modified any fields before submitting?", Toast.LENGTH_SHORT).display();
                    }
                } else {
                    Toast.makeText(this, "Error occured, please try again later.", Toast.LENGTH_SHORT).display();
                }
            } catch (JSONException ex) {
                Logger.getLogger(SchedulePanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jbtMSubmitActionPerformed

    private void jrbMActiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbMActiveActionPerformed
        status = evt.getActionCommand();
    }//GEN-LAST:event_jrbMActiveActionPerformed

    private void jrbMInactiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbMInactiveActionPerformed
        status = evt.getActionCommand();
    }//GEN-LAST:event_jrbMInactiveActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.ButtonGroup jbgAStatus;
    private javax.swing.ButtonGroup jbgMStatus;
    private javax.swing.JButton jbtAClear;
    private javax.swing.JButton jbtASubmit;
    private javax.swing.JButton jbtAddSchedule;
    private javax.swing.JButton jbtMSubmit;
    private javax.swing.JButton jbtModifySchedule;
    private javax.swing.JComboBox jcbxAActiveRoute;
    private javax.swing.JComboBox jcbxATrain;
    private javax.swing.JComboBox jcbxMActiveRoute;
    private javax.swing.JComboBox jcbxMTrain;
    private javax.swing.JLabel jlblADepartureTime;
    private javax.swing.JLabel jlblAScheduleName;
    private javax.swing.JLabel jlblASelectRoute;
    private javax.swing.JLabel jlblAStatus;
    private javax.swing.JLabel jlblATrain;
    private javax.swing.JLabel jlblMDepartureTime;
    private javax.swing.JLabel jlblMScheduleName;
    private javax.swing.JLabel jlblMSelectRoute;
    private javax.swing.JLabel jlblMStatus;
    private javax.swing.JLabel jlblMTrain;
    private javax.swing.JLabel jlblScheduleTitle;
    private javax.swing.JPanel jpAddArrow;
    private javax.swing.JPanel jpAddCard;
    private javax.swing.JPanel jpAddSchedule;
    private javax.swing.JPanel jpModifyArrow;
    private javax.swing.JPanel jpModifyCard;
    private javax.swing.JPanel jpModifySchedule;
    private javax.swing.JPanel jpNullCard;
    private javax.swing.JPanel jpSchedule;
    private javax.swing.JPanel jpScheduleArrow;
    private javax.swing.JPanel jpScheduleCard;
    private javax.swing.JPanel jpScheduleContent;
    private javax.swing.JRadioButton jrbAActive;
    private javax.swing.JRadioButton jrbAInactive;
    private javax.swing.JRadioButton jrbMActive;
    private javax.swing.JRadioButton jrbMInactive;
    private javax.swing.JScrollPane jspScheduleScroller;
    private javax.swing.JSpinner jspiADepartureTime;
    private javax.swing.JSpinner jspiMDepartureTime;
    private javax.swing.JSeparator jsprSchedule;
    private javax.swing.JTable jtbSchedule;
    private javax.swing.JTextField jtfAScheduleName;
    private javax.swing.JTextField jtfMScheduleName;
    // End of variables declaration//GEN-END:variables
}
